#include "StatusServiceImpl.hpp"
#include <boost/asio.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/system/error_code.hpp>
#include <exception>
#include <grpcpp/grpcpp.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <iostream>
#include <json/json.h>
#include <json/reader.h>
#include <json/value.h>
#include <memory>
#include <thread>
boost::property_tree::ptree config;
void RunServer() {
  std::string server_address(config.get<std::string>("StatusServer.Host") +
                             ":" +
                             config.get<std::string>("StatusServer.Port"));
  StatusServiceImpl service;
  grpc::ServerBuilder builder;
  // 监听端口和添加服务
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);

  // 构建并启动gRPC服务器
  std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;

  // 创建Boost.Asio的io_context
  boost::asio::io_context io_context;
  // 创建signal_set用于捕获SIGINT
  boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
  // 设置异步等待SIGINT信号
  signals.async_wait(
      [&io_context, &server](const boost::system::error_code &error,
                             int signal_number) {
        if (!error) {
          std::cout << "Shutting down server..." << std::endl;
          server->Shutdown();
          io_context.stop();
        }
      });
  // 在单独的线程中运行io_context
  std::thread([&io_context]() { io_context.run(); }).detach();
  // 等待服务器关闭
  server->Wait();
}
int main() {
  try {
    boost::property_tree::ini_parser::read_ini("./config.ini", config);
    RunServer();
  } catch (std::exception &e) {
    std::cout << e.what();
  }

  return 0;
}
